package com.xci.platform.helper;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Excel操作帮助类
 */
public class ExcelHelper {

    /**
     * Web导出Excel
     * @param response http响应对象
     * @param data 导出的数据
     * @param pojoClass 实体对象类型
     * @param title 标题
     * @throws IOException IO异常
     */
    public static void exportWeb(HttpServletResponse response,@NotNull List data, Class<?> pojoClass, String title) throws IOException {

        ExportParams exportParams = new ExportParams(title, title, ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, data);
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Content-Type", "application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title + ".xlsx", "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        Sheet sheet = workbook.getSheetAt(0);
        // if (sheet != null && isAutoSizeColumn) {
        //     ExcelUtil.autoSizeExcelColumn(sheet);
        // }
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 自适应excel单元格
     *
     * @param sheet excel
     */
    public static void autoSizeExcelColumn(Sheet sheet) {
        for (int columnNum = 0; columnNum <= 8; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                Row currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(columnNum) != null) {
                    Cell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }
}
